package model.persistence.dao;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import model.persistence.vo.Sessao;
import org.hibernate.Criteria;
import org.hibernate.Query;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;

public class HibernateDAO implements IDAO {
    
    private Class classeVO;
    
    public HibernateDAO(Class classeVO) {
        super();
        this.classeVO = classeVO;
    }
    
    public Serializable save(Object e) {
        Session session = HibernateUtil.getSession();
        Transaction t = session.beginTransaction();
        Serializable savedId = (Serializable) session.save(e);
        t.commit();
        return savedId;
    }
    
    public void saveOrUpdate(Object e) {
        Session session = HibernateUtil.getSession();
        Transaction t = session.beginTransaction();
        session.saveOrUpdate(e);
        t.commit();
    }
    
    public void delete(Object e) {
        Session session = HibernateUtil.getSession();
        Transaction t = session.beginTransaction();
        session.delete(e);
        t.commit();
    }
    
    public Object select(Serializable id) {
        Session session = HibernateUtil.getSession();
        return (Object) session.get(classeVO, id);
    }
    
    public Collection selectAll() {
        Session session = HibernateUtil.getSession();
        
        Collection collection = (Collection) session.createCriteria(classeVO).list();
        
        return collection;
    }
    
    public Class getClasseVO() {
        return classeVO;
    }        
    
    public void setClasseVO(Class classeVO) {
        this.classeVO = classeVO;
    }
    
    public void save(Collection entities) {
        for (Object entity : entities) {
            save(entity);
        }
    }
            
    public Collection selectBy(SimpleExpression s) {
        Session session = HibernateUtil.getSession();
        Criteria crt = session.createCriteria(classeVO);
        crt.add(s);
        return crt.list();        
    }
    
    public Collection selectBy(Criterion c) {
        Session session = HibernateUtil.getSession();
        Criteria crt = session.createCriteria(classeVO);
        crt.add(c);
        return crt.list();
    }
}
